import { message } from "antd";
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import showError from "./showError";

interface resProps<T = any> {
    code: number,
    message: string;
    data: T
}

// 创建实例进行配置，不影响全局的axios
const instance = axios.create({
    withCredentials: true, // 允许发送 cookie
    timeout: 1000 * 60 * 60,
});

// 添加请求拦截器
instance.interceptors.request.use((config: any) => {
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const headers = {
        ...config.headers,
        'Content-Type': 'application/json',
        authorizationtoken: user.token,
    };
    config.url = `http://${window.location.hostname}:3000/api${config.url}`
    return { ...config, headers };
}, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use((response) => {
    //这里统一处理后端报错
    if (response.data.code !== 200 && response.data.code !== 401) {
        showError(response.data);
    }
    // 对响应数据做点什么
    return response;
}, (error) => {
    // 对响应错误做点什么
    message.error(error.message)
    return Promise.resolve({
        ...error,
        data: {
            code: error.status,
            message: "非200错误！"

        }
    });
});
const request = async <T = any>(config: AxiosRequestConfig): Promise<resProps<T>> => {
    const response = await instance.request<resProps<T>>(config);
    return response.data;
};
export default request